﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using Argos.Scheduling;

namespace Argos.Design
{
	/// <summary>
	/// Converts <see cref="TimeOfDay"/> instances to and from strings.
	/// </summary>
	public sealed class TimeOfDayConverter : TypeConverter
	{

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			return sourceType == typeof(string) || sourceType == typeof(InstanceDescriptor);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			return destinationType == typeof(string) || destinationType == typeof(InstanceDescriptor);
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (value is string)
			{
				return TimeOfDay.Parse((string)value);
			}
			if (value is InstanceDescriptor)
			{
				return base.ConvertFrom(context, culture, value);
			}

			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (null == destinationType)
			{
				throw new ArgumentNullException("destinationType");
			}

			if (value is TimeOfDay)
			{
				TimeOfDay t = (TimeOfDay)value;
				if (destinationType == typeof(string))
				{
					return t.ToString();
				}
				if (destinationType == typeof(InstanceDescriptor))
				{
					object[] args = new object[] { t.Hour, t.Minute, t.Second, t.Millisecond, t.Kind };
					ConstructorInfo constructor = typeof(TimeOfDay).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(TimeKind) });
					return new InstanceDescriptor(constructor, args, true);
				}
			}

			return base.ConvertTo(context, culture, value, destinationType);
		}
	}
}
